package liangtWorkSpace.simple;

import java.util.Stack;

/**
 * @ClassName IsValid
 * @Description : 验证是否匹配括号
 * @Author : LiangT
 * @Date : 2020/6/14 12:32
 */
public class IsValid {
    /**
     * 逐个删除匹配括号，最后剩余的就是不匹配的
     *
     * @param s
     * @return
     */
    public boolean isValid(String s) {
        if(s.length() %2 != 0){
            return false;
        }
        int t = s.length() /2;

        while(t > 0){
            s = s.replace("()","").replace("[]","").replace("{}","");
            t--;
        }
        return s.isEmpty();
    }

    /**
     *
     * @param s
     * @return
     */
    public boolean isValid2(String s) {
        if(s.length() %2 != 0){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();

        for (char aChar: chars){
            if (stack.size() == 0){
                stack.push(aChar);
            }else if (isSym(stack.peek(),aChar)){
                stack.pop();
            }else {
                stack.push(aChar);
            }
        }
        return stack.size() == 0;
    }

    /**
     *
     * @param peek
     * @param aChar
     * @return
     */
    private boolean isSym(Character peek, char aChar) {
        return (peek == '(' && aChar == ')') || (peek == '{' && aChar == '}')||(peek == '[' && aChar == ']');
    }
}
